import { WeaUpload } from 'ecCom';
import { Button, message } from "antd";
import { isArray } from 'lodash';
import { toJS } from 'mobx';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { uploadPicPngImg, requiredPngImg } from '.';
import { WeaLocaleProvider } from 'ecCom';
import LeftMenuStore from '../../form/LeftMenuStore';

const getLabel = WeaLocaleProvider.getLabel;
const oldrefreshContent = window.GC.Spread.Sheets.FloatingObjects.Picture.prototype.refreshContent;
window.GC.Spread.Sheets.FloatingObjects.Picture.prototype.canDelete = false;
window.GC.Spread.Sheets.FloatingObjects.Picture.prototype.allowDelete = function (a) { this.canDelete = a };
window.GC.Spread.Sheets.FloatingObjects.Picture.prototype.deleteSelf = function () { }
window.GC.Spread.Sheets.FloatingObjects.Picture.prototype.setDeleteSelf = function (a) { this.deleteSelf = a };
window.GC.Spread.Sheets.FloatingObjects.Picture.prototype.refreshContent = function (a) {
    oldrefreshContent.apply(this, arguments);
    if (this.canDelete) {
        const div = document.createElement("div");
        const dom = this.getHost()[0];
        if (dom && !dom.hasChildNodes()) {
            div.className = "edc-excel-pic-delete";
            div.innerHTML = '<div style="color:#fff">删除</div>';
            div.addEventListener('click', this.deleteSelf)
            dom.appendChild(div);
        }
    }
}
export default class WeaPicCellType extends GC.Spread.Sheets.CellTypes.Base {
    typeName = 'WeaPicCellType';
    fieldType;
    viewAttr = 2;
    label;
    clickwidth;
    loading = false;
    imageWidth = "";
    imageHeight = "";
    containerId = "";
    secId = "";
    joinCubeFlag = false;
    id;
    multilang;
    fieldVisible;
    paint(ctx, value, x, y, w, h, style, context) {
        if (this.fieldVisible == '1') {
            this.viewAttr = 1;
            return;
        }
        if (!ctx) {
            return;
        }
        if (this.viewAttr != 1) {
            let iconWidth = 16;
            if(this.iconWidth) iconWidth = this.iconWidth;
            super.paint(ctx, value, x, y, w - 20, h, style, context);
            super.paint(ctx, '', x + w - 20, y, 20, h, style, context);
            const width = Math.min(iconWidth, h);
            if (this.viewAttr == 2) {
                this.clickwidth = width;
                ctx.drawImage(uploadPicPngImg, x + w - width, y + (h - width) / 2, width, width);
            } else if (this.viewAttr == 3) {
                if (value && value.length > 0) {
                    this.clickwidth = width;
                    ctx.drawImage(uploadPicPngImg, x + w - width, y + (h - width) / 2, width, width);
                } else {
                    this.clickwidth = width + 9;
                    ctx.drawImage(uploadPicPngImg, x + w - this.clickwidth, y + (h - width) / 2, width, width);
                    ctx.drawImage(requiredPngImg, x + w - 8, y + (h - 7) / 2, 7, 7);
                }
            }
        } else {
            super.paint(ctx, value, x, y, w, h, style, context);
        }
    }
    format(value, format, formattedData, context) {
        return '';
    }

    fromJSON(setting, context, row, sheet) {
        this.fieldType = toJS(setting.fieldType);
        if (this.fieldType) {
            this.imageWidth = this.fieldType[2];
            this.imageHeight = this.fieldType[3];
        }
        this.viewAttr = setting.viewAttr;
        this.fieldVisible = setting.fieldVisible;
        this.label = setting.label;
        this.secId = setting.secId;
        this.joinCubeFlag = setting.joinCubeFlag;
        this.id = setting.id;
        this.multilang = setting.multilang;
    }

    getHitInfo(x, y, cellStyle, cellRect, context) {
        const { row, col, sheetArea, sheet } = context;
        return {
            x,
            y,
            row,
            col,
            cellRect,
            sheetArea,
            sheet,
        };
    }

    processMouseUp(hitInfo) {
        // 只读 不展示
        if (this.viewAttr && this.viewAttr == 1) {
            return;
        }
        const { context, x, y, cellRect, sheet, row, col, sheetArea, reservedLocation, isReservedLocation } = hitInfo;

        if (x && cellRect) {
            if (x >= cellRect.x + cellRect.width - this.clickwidth) {
                //定位点击图标的位置
                this.showBrowserModal(sheetArea, sheet, row, col, x, y, cellRect);
            }
            return true;
        }
        return super.processMouseUp(hitInfo);
    }

    showBrowserModal(sheetArea, sheet, row, col, x, y, cellRect) {
        // 只读 不展示
        if (this.viewAttr && this.viewAttr == 1) {
            return;
        }
        this.renderUpload(cellRect.x, cellRect.y, sheet, row, col, sheetArea);
    }

    /**
     * 实现将图片转化成base64
     */
    convertImgToBase64(url, callback, outputFormat) {
        const doIt = () => {
            canvas.height = img.height;
            canvas.width = img.width;
            ctx.drawImage(img, 0, 0);
            var dataURL = canvas.toDataURL(outputFormat || 'image/png');
            callback.call(this, dataURL);
            canvas = null;
        }
        let canvas = document.createElement('CANVAS'),
            ctx = canvas.getContext('2d'),
            img = new Image;
        img.crossOrigin = 'Anonymous';
        img.src = url;
        if (img.complete) {
            doIt();
        } else {
            img.onload = function () {
                doIt();
            };
        }
    }

    /**
     * 渲染图片上传控件
     */
    renderUpload = (x, y, sheet, row, col, sheetArea) => {
        let editor;
        if (!editor) {
            editor = document.createElement('div');
            const host = sheet.getCell(row, col, sheetArea).sheet.getParent().getHost();
            host.appendChild(editor);
            editor.style.visibility = 'hidden';
            $(editor).css({
                position: 'absolute',
                left: x,
                top: y,
                width: 100,
                height: 50,
            });
        }
        ReactDOM.unmountComponentAtNode(editor);
        const replaceDatas = sheet.getCell(row, col, sheetArea).value() || [];
        const changeValue = (ids, list) => {
            const cell = sheet.getCell(row, col);
            let fileList = list.filter(obj => {
                const fileid = obj.fileid;
                const picName = `f,${row},${col},${fileid}`;
                const picObj = sheet.floatingObjects.get(picName);
                return !(picObj && !picObj.isVisible());
            }) || [];
            fileList = fileList.map(obj => ({ fileid: obj.fileid, imagefileid: obj.imagefileid }));
            cell.value(fileList);
        }
        if (this.joinCubeFlag && (!this.secId || this.secId == "0")) {
            message.error(getLabel('388817', '附件上传目录未设置！'));
        } else {
            let browserInstance;
            ReactDOM.render(
                <div className="required"><WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@ywsyg6`}
                    ref={(ref) => browserInstance = ref}
                    viewAttr={3}
                    uploadUrl={"/api/edc/upload/uploadFile2Doc"}
                    uploadParams={{ secId: this.secId }}
                    category="string"
                    listType="list"
                    limitType="jpg,jpeg,png,gif,bmp,psd,tif"
                    isDetail={true}
                    datas={replaceDatas}
                    showClearAll={false}
                    onChange={changeValue}
                    onUploading={status =>
                        this.loading = (status === "uploading")
                    }
                >
                </WeaUpload>
                </div>, editor);
            const btnClick = () => {
                if (browserInstance) {
                    const id = browserInstance.state.containerId;
                    this.containerId = id;
                    document.getElementById('browsebtn__' + id).click();
                } else {
                    setTimeout(() => {
                        btnClick();
                    }, 50);
                }
            }
            setTimeout(() => {
                btnClick();
            }, 50);
        }
    }

    /**
     * 展示图片浮动层
     */
    showPic = (list, context) => {
        if (list.length == 0) return;
        const { row, col, sheetArea, sheet } = context;
        sheet.suspendPaint();
        sheet.options.isProtected = true;
        const windowWidth = sheet.getParent().getHost().clientWidth
        const num = Math.floor((windowWidth - 50) / (10 + Number(this.imageWidth)));
        let width = Number(this.imageWidth);
        if (list.length > num) {
            width = Math.floor((windowWidth - 150) / (list.length)) - 10;
        }
        const height = Math.floor(width / Number(this.imageWidth) * Number(this.imageHeight));
        const span = sheet.getSpan(row, col);
        let colCount = 1;
        let rowCount = 1;
        if (span) {
            rowCount = span.rowCount;
            colCount = span.colCount;
        }
        if (!this.oldOptions) {
            this.oldOptions = {};
            this.oldOptions.rowHeights = {};
            this.oldOptions.colWidths = {};
            let countHeight = 0;
            for (let j = 0; j < rowCount; j++) {
                const currentRow = row + j;
                const rowHeight = sheet.getRowHeight(currentRow, sheetArea);
                this.oldOptions.rowHeights[currentRow] = rowHeight;
                countHeight += rowHeight;
            }
            let countWidth = 0;
            for (let j = 0; j < colCount; j++) {
                const currentCol = col + j;
                const colWidth = sheet.getColumnWidth(currentCol, sheetArea);
                this.oldOptions.colWidths[currentCol] = colWidth;
                countWidth += colWidth;
            }

            this.oldOptions.countHeight = countHeight;
            this.oldOptions.countWidth = countWidth;
        }
        const { countHeight, countWidth } = this.oldOptions;
        const setRowHeight = (countRowHeight) => {
            if (countRowHeight > countHeight) {
                const perHeight = (countRowHeight - countHeight) / rowCount;
                for (let j = 0; j < rowCount; j++) {
                    const currentRow = row + j;
                    const rowHeight = this.oldOptions ? this.oldOptions.rowHeights[currentRow] : sheet.getRowHeight(currentRow, sheetArea);
                    if(rowHeight + perHeight>sheet.getRowHeight(currentRow, sheetArea))
                        sheet.setRowHeight(currentRow, rowHeight + perHeight);
                }

            }
        }
        const setColumnWidth = (countColumnWidth) => {
            if (countColumnWidth > countWidth) {
                const perWidth = (countColumnWidth - countWidth) / colCount;
                for (let j = 0; j < colCount; j++) {
                    const currentCol = col + j;
                    const colWidth = this.oldOptions ? this.oldOptions.colWidths[currentCol] : sheet.getColumnWidth(currentCol, sheetArea); 
                    if(colWidth+perWidth>sheet.getColumnWidth(currentCol, sheetArea))
                        sheet.setColumnWidth(currentCol, colWidth + perWidth);
                }
            }
        }
        setRowHeight(height);
        setColumnWidth((10 + Number(width)) * list.length + 50);

        list.map((obj, index) => {
            const imagefileid = obj.imagefileid;
            const url = "/weaver/weaver.file.FileDownload?fileid=" + imagefileid;
            let left = index * (Number(width) + 10) + 10;
            this.convertImgToBase64(url, function (base64Img) {
                const name = 'f,' + String(row) + ',' + String(col) + ',' + obj.fileid;
                let picture = sheet.pictures.get(name);
                if (!picture) {
                    picture = sheet.pictures.add(name);
                }
                picture.src(base64Img);
                picture.startRow(row);
                picture.startColumn(col);
                if (index > 0 && colCount > 1) {
                    const { colIndex, leftWidth } = this.getColIndex(context, colCount, index * Number(width));
                    if (colIndex >= col + colCount) {
                        picture.startColumn(col + colCount - 1);
                        left = left - preWidth;
                    } else {
                        picture.startColumn(colIndex);
                        left = leftWidth;
                    }
                }
                picture.startRowOffset(0);
                picture.startColumnOffset(left);
                picture.height(Number(height))
                picture.width(Number(width))
                picture.allowDelete(this.viewAttr > 1);
                const del = () => {
                    this.deletePic(row, col, obj.fileid);
                }
                picture.setDeleteSelf(del);
                picture.isVisible(true);
            });
        })
        sheet.resumePaint();
    }


    getColIndex = (context, colCount, width) => {
        const { row, col, sheetArea, sheet } = context;
        let count = 0;
        for (var l = 0; l < colCount; l++) {
            const cur = sheet.getColumnWidth(col + l, sheetArea);
            count += cur
            if (count >= width) {
                return { colIndex: col + l, leftWidth: width - (count - cur) };
            }
        }
    }

    deletePic = (row, col, id) => {
        workbookInstance.commandManager().execute({
            cmd: 'edc.excelView.deletePic',
            sheet: workbookInstance.getActiveSheet(),
            row,
            col,
            id,
        });
    }

}